package net.huashitong.gradePoint.web;

import com.sirdc.modules.core.config.Global;
import com.sirdc.modules.core.web.JsonBaseController;
import com.sirdc.modules.core.web.model.JqGrid;
import com.sirdc.modules.core.web.model.Message;

import com.sirdc.modules.sys.entity.SysDept;
import com.sirdc.modules.sys.entity.SysUser;
import com.sirdc.modules.sys.security.SysPrincipal;
import com.sirdc.modules.sys.service.SysUserService;
import com.sirdc.modules.sys.util.SysUserUtils;
import com.sirdc.modules.utils.NumberUtils;
import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import net.huashitong.gradePoint.entity.GradePoint;
import net.huashitong.gradePoint.entity.ScoreSummary;
import net.huashitong.gradePoint.entity.SysBnpFile;
import net.huashitong.gradePoint.filter.GradePointFilter;
import net.huashitong.gradePoint.filter.ScoreSummaryFilter;
import net.huashitong.gradePoint.service.GradePointService;
import net.huashitong.gradePoint.service.ScoreSummaryService;
import net.huashitong.gradePoint.service.SysBnpFileService;
import net.huashitong.taskjob.service.SupervisionService;
import net.huashitong.taskjob.util.UtilsTools;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriUtils;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.*;

/**
 * 绩点考核
 */
@Controller
@RequestMapping("/gradepoint")
public class GradePointCtrl extends JsonBaseController {

    @Autowired
    GradePointService gradePointService;
    @Autowired
    private SupervisionService supervisionService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ScoreSummaryService scoreSummaryService;
    @Autowired
    private SysBnpFileService fileservice;

    @Override
    protected String getView(String s) {
        return "/modules/sys/gradepoint/" + s;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String initPage(HttpServletRequest request, Model model) {
//        model.addAttribute("leftType", "绩效考核");
//        BnpUser bnpUser = (BnpUser) WebUtils.getSessionAttribute(request, "user");
//        if (ObjectUtils.isBlank(bnpUser)) {
//            return "/modules/login/login";
//        }
//        int myTaskNum = (int) WebUtils.getSessionAttribute(request, "myTaskNum");
//        int quetionNum = (int) WebUtils.getSessionAttribute(request, "quetionNum");
//        model.addAttribute("myTaskNum", myTaskNum);
//        model.addAttribute("quetionNum", quetionNum);
//        int nodeCount = (int) WebUtils.getSessionAttribute(request, "nodeCount");
//        model.addAttribute("nodeCount", nodeCount);
//        model.addAttribute("user", bnpUser);
        return getView("query");
    }

    /**
     * 初始化数据
     *
     * @param filter
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST)
    public JqGrid query(@ModelAttribute GradePointFilter filter, HttpServletRequest request, Model model) {

        List<SysDept> jobGroups = supervisionService.queryAllSupervisions();
        SysPrincipal bnpUser = SysUserUtils.getSysPrincipal();
        filter.setCheckObjectId(bnpUser.getUserId());
        if (StringUtils.isNotBlank(filter.getCheckType())) {
            if (filter.getPaging().getCurrentPage() == 1) {
                List<GradePoint> allList = gradePointService.queryGradePointByCheckType(filter.getCheckType());
                Collections.sort(allList, new Comparator<GradePoint>() {
                    @Override
                    public int compare(GradePoint g1, GradePoint g2) {
                        double score1 = Double.parseDouble(StringUtils.isBlank(g1.getSoucre()) ? "0" : g1.getSoucre());
                        double score2 = Double.parseDouble(StringUtils.isBlank(g2.getSoucre()) ? "0" : g2.getSoucre());
                        if (score1 < score2) {
                            return 1;
                        } else if (score1 == score2) {
                            return 0;
                        } else {
                            return -1;
                        }
                    }
                });
                for (int i = 0, s = allList.size(); i < s; i++) {
                    if (i > 0 && Double.parseDouble(StringUtils.isBlank(allList.get(i).getSoucre()) ? "0" : allList.get(i).getSoucre())
                            == Double.parseDouble(StringUtils.isBlank(allList.get(i - 1).getSoucre()) ? "0" : allList.get(i - 1).getSoucre())) {
                        allList.get(i).setTypeRank(allList.get(i - 1).getTypeRank());
                    } else {
                        allList.get(i).setTypeRank(i + 1 + "");
                    }
                }
                gradePointService.batchUpdate(allList);
            }
            List<GradePoint> lists = gradePointService.queryGradePoint(filter);
            for (GradePoint gradePoint : lists) {
                gradePoint.setRank(gradePoint.getTypeRank());
            }
            return coverJqGrid(filter, lists);
        }

        //==========================================================================================================

        List<GradePoint> lists = gradePointService.queryGradePoint(filter);
        return coverJqGrid(filter, lists);
    }


    /**
     * 查询页面
     *
     * @param filter
     * @return
     */
    @RequestMapping("/filter")
    public String filter(@ModelAttribute GradePointFilter filter) {
        return getView("filter");
    }

    @RequestMapping(value = "/showDetail/{id}", method = RequestMethod.GET)
    public String showEdit(Model model, @PathVariable String id) {
        GradePoint gradePoint = gradePointService.getById(id);
        model.addAttribute("gradePoint", gradePoint);
        return getView("showDetail");
    }

    @RequestMapping("/formHead")
    public String showHead() {
        return getView("formHead");
    }

    @ResponseBody
    @RequestMapping(value = "/getScoreAndRank", method = RequestMethod.GET)
    public Message getScoreAndRank(HttpServletRequest request) {

        Map<String, String> resultMap = new HashMap<>();

        String branchType = "——";
        SysPrincipal bnpUser = SysUserUtils.getSysPrincipal();
        String checkObjectId = bnpUser.getUserId();
        SysUser sysUser = sysUserService.getById(bnpUser.getUserId());
        //督查标志		0是督查组	1是责任人
        if ("1".equals(sysUser.getSuperFlag())) {
            branchType = "责任单位";
        }
        if ("0".equals(sysUser.getSuperFlag())) {
            branchType = "督查组";
        }

        //单独出来的一个汇总信息
        if ("0".equals(sysUser.getSuperFlag()) || "1".equals(sysUser.getSuperFlag())) {
            ScoreSummaryFilter scoreSummaryFilter = new ScoreSummaryFilter();
            scoreSummaryFilter.setUserId(checkObjectId);
            List<ScoreSummary> scoreSummaries = scoreSummaryService.queryByFilterNoPage(scoreSummaryFilter);
            if (ObjectUtils.isNotBlank(scoreSummaries)) {
                ScoreSummary summary = scoreSummaries.get(0);
                resultMap.put("finalScore", StringUtils.isBlank(summary.getScore()) ? "——" : NumberUtils.keepPrecision(summary.getScore(), 2) + "");   //最终得分
                resultMap.put("finalRank", StringUtils.isBlank(summary.getRank()) ? "——" : summary.getRank());     //最终排名
                resultMap.put("itemRank", StringUtils.isBlank(summary.getTypeRank()) ? "——" : summary.getTypeRank());  //组内排名
                resultMap.put("name", StringUtils.isBlank(bnpUser.getName()) ? "——" : bnpUser.getName());          //名字
                SysDept sysDept = scoreSummaryService.queryDeptByUserId(bnpUser.getUserId());
                resultMap.put("branch", ObjectUtils.isBlank(sysDept) ? "——" : sysDept.getDeptName());      //组别
                resultMap.put("branchType", branchType);      //组别
                return coverMessage("200", "操作成功", resultMap);
            }
            return coverMessage("201", "操作成功", resultMap);
        }else{
            return coverMessage("201", "操作成功", resultMap);
        }

    }


    @RequestMapping(value = "/download/{id}")
    public void downProjectfile(@PathVariable String id, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        downLoadFile(id, req, resp);
    }

    public void downLoadFile(String fileId, HttpServletRequest req, HttpServletResponse resp) throws Exception {
        SysBnpFile sysBnpFile = fileservice.getById(fileId);
        if (sysBnpFile == null) {
            throw new Exception(" current request path is empty");
        }
        String filepath = sysBnpFile.getUrl();
        int index = filepath.lastIndexOf(Global.USER_DIR);
        if (index >= 0) {
            filepath = filepath.substring(index + Global.USER_DIR.length());

        }
        try {
            filepath = UriUtils.decode(filepath, "UTF-8");
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            logger.error(String.format("解释文件路径失败，URL地址为%s", filepath), e1);
        }
        File file = new File(Global.getUploadBaseDir() + filepath);
        try {
            String fileName = "《绩效考核评分方案》";
            String n = new String(fileName.getBytes(), "iso8859-1");
            resp.setHeader("Content-Type", "application/octet-stream");
            resp.setHeader("Content-Disposition", "attachment; filename=" + n + "." + sysBnpFile.getFileType());
            FileCopyUtils.copy(new FileInputStream(file), resp.getOutputStream());
            return;
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            throw new FileNotFoundException("请求的文件不存在");
        }
    }
}
